/**
 * 初始化 BootStrap Table 特殊封装的封装
 *
 * 约定：toolbar的id为 (bstableId + "Toolbar")
 *
 * @author cyf
 */
(function () {
    var CTDBSTable = function (bstableId, url, columns) {
        this.btInstance = null;					//jquery和BootStrapTable绑定的对象
        this.bstableId = bstableId;
        this.url = url;
        this.method = "post";
        this.paginationType = "server";			//默认分页方式是服务器分页,可选项"client"
        this.pageSize = "10";	//每页显示条数
        this.toolbarId = bstableId + "Toolbar";
        this.columns = columns;
        this.data = {};
        this.queryParams = {}; // 向后台传递的自定义参数
        this.exportDataType = "all";//默认导出所有数据
        this.ignoreColumn = "[]";
        this.exportFileName = "信息列表";
        this.exportTableName = "信息列表";
        this.singleSelect = false;
        this.showColumns = false;
        this.showRefresh = false;
        this.showToggle = false;
        this.showExport = false;
        this.sortName = undefined;
        this.sortOrder = "desc";
        this.search = false;      		//是否显示表格搜索，此搜索是客户端搜索，不会进服务端
        this.strictSearch = false;		//设置为 true启用 全匹配搜索，否则为模糊搜索
        this.height = 0,						//默认表格高度665
            this.subHeight = 0;
        this.subHead = 0;
        this.pagination=true;
        this.onClickRow = false;
        this.onDblClickRow = false;
        this.onLoadSuccess = false;
        this.rowStyle = function(row,index){
            return {css:{}}
        };
    };

    CTDBSTable.prototype = {
        /**
         * 初始化bootstrap table
         */
        init: function () {
            var self = this;
            if(this.height==0){
                this.autoHeight();
            }
            var tableId = this.bstableId;
            var that = this;    //为传参queryParams 2021.04.12 jumper
            this.btInstance =
                $('#' + tableId).bootstrapTable({
                    contentType: "application/x-www-form-urlencoded",
                    autoSizeColumn:true,
                    url: this.url,				//请求后台的URL（*）
                    method: this.method,		//ajax方式,post还是get
                    ajaxOptions: {				//ajax请求的附带参数
                        data: this.data
                    },
                    toolbar: "#" + this.toolbarId,//顶部工具条,工具按钮用哪个容器
                    striped: true,     			//是否显示行间隔色
                    cache: false,      			//是否使用缓存,默认为true
                    singleSelect: this.singleSelect,		// 单选checkbox
                    pagination: this.pagination,     		//是否显示分页（*）
                    sortName: this.sortName,      		//排序字段
                    sortable: true,      		//是否启用排序
                    sortOrder: this.sortOrder,     		//排序方式
                    pageNumber: 1,      			//初始化加载第一页，默认第一页
                    pageSize: this.pageSize,      			//每页的记录行数（*）
                    pageList: [10,20,30],  	//可供选择的每页的行数（*）
                    paginationHAlign: 'right', //right, left
                    paginationVAlign: 'bottom', //bottom, top, both
                    paginationDetailHAlign: 'left', //right, left
                    paginationPreText: '上一页',
                    paginationNextText: '下一页',
                    queryParamsType: 'limit', 	//默认值为 'limit' ,在默认情况下 传给服务端的参数为：offset,limit,sort
                    queryParams: function (param) {
                        return $.extend(that.queryParams, param);
                    }, // 向后台传递的自定义参数
                    sidePagination: this.paginationType,   //分页方式：client客户端分页，server服务端分页（*）
                    search: this.search,      		//是否显示表格搜索，此搜索是客户端搜索，不会进服务端
                    strictSearch: this.strictSearch,			//设置为 true启用 全匹配搜索，否则为模糊搜索
                    showColumns: this.showColumns,     		//是否显示所有的列
                    showRefresh: this.showRefresh,     		//是否显示刷新按钮
                    showToggle: this.showToggle,                    //是否显示详细视图和列表视图的切换按钮
                    minimumCountColumns: 1,    	//最少允许的列数
                    clickToSelect: true,    	//是否启用点击选中行
                    searchOnEnterKey: true,		//设置为 true时，按回车触发搜索方法，否则自动触发搜索方法
                    columns: this.columns,		//列数组
                    height: this.height,		//高度(undefined或null:分页位置不固定，与内容无间距，auto:分页位置不固定，与内容有间距)
                    rowStyle:this.rowStyle,
                    icons: {
                        refresh: 'hisui-icon icon-reload',
                        toggle: 'hisui-icon icon-paper',
                        columns: 'hisui-icon icon-paper-arrow-down'
                    },
                    iconSize: 'outline',
                    showExport: this.showExport,                     //是否显示导出按钮
                    exportTypes:['csv', 'txt', 'sql', 'doc', 'excel', 'xlsx', 'pdf'],           //导出文件类型
                    exportDataType: this.exportDataType,             //basic当前页', 'all所有, 'selected'.
                    exportOptions: {
                        ignoreColumn: this.ignoreColumn,  //忽略某一列的索引
                        fileName: this.exportFileName,  //文件名称设置
                        worksheetName: 'sheet1',  //表格工作区名称
                        tableName: this.exportTableName,
                        excelstyles: ['background-color', 'color', 'font-size', 'font-weight']
                    },
                    onClickRow:function(row, $ele, field){
                        if(self.onClickRow){
                            self.onClickRow(row, $ele, field);
                        }
                    },
                    onDblClickRow:function(row, $ele, field){
                        if(self.onDblClickRow){
                            self.onDblClickRow(row, $ele, field);
                        }
                    },
                    onLoadSuccess: function(data){  //加载成功时执行
                        $('#' + tableId+" > tbody td").each(function(index){
                            $(this).attr("title",$(this).text());
                        })
                        var elements =$('#' + tableId+" > tbody").find(".btnMore");
                        elements.each(function() {
                            if ($(this).attr("data-mouseover-binded") == undefined) {
                                $(this).attr("data-mouseover-binded", true);
                                var timeoutHover;
                                elements.mouseover(function() {
                                    var more = $(this),
                                        items = more.next(),
                                        pos = more.position(),
                                        top = pos.top - items.height() / 2 + 9,
                                        left = pos.left - items.width() - 15;
                                    if (!items.hasClass("moreItems")) {
                                        return
                                    }
                                    $('#' + tableId+" > tbody").find(".btnMore.open").removeClass("open").find("i").removeClass("fa-chevron-circle-left").addClass("fa-chevron-circle-right");
                                    $('#' + tableId+" > tbody").find(".moreItems.open").removeClass("open").hide();
                                    more.addClass("open").find("i").removeClass("fa-chevron-circle-right").addClass("fa-chevron-circle-left");
                                    items.addClass("open").css({
                                        top: top,
                                        left: left
                                    }).show();
                                    if (items.attr("data-hover-binded") == undefined) {
                                        items.attr("data-hover-binded", true);
                                        items.hover(function() {
                                            window.clearTimeout(timeoutHover)
                                        }, function() {
                                            window.clearTimeout(timeoutHover);
                                            timeoutHover = window.setTimeout(function() {
                                                more.removeClass("open").find("i").removeClass("fa-chevron-circle-left").addClass("fa-chevron-circle-right");
                                                items.hide()
                                            }, 500)
                                        }).find("a").click(function() {
                                            more.removeClass("open").find("i").removeClass("fa-chevron-circle-left").addClass("fa-chevron-circle-right");
                                            items.hide()
                                        })
                                    }
                                })
                            }
                        });
                        if(self.onLoadSuccess){
                            self.onLoadSuccess(data);
                        }
                    }
                });
            return this;
        },
        autoHeight:function(){
            var self = this;
            var t_top =$('#'+self.bstableId).offset().top;
            var b_height = document.documentElement.clientHeight;

            self.height = b_height-t_top+self.subHeight-self.subHead+18;
            /*
            var resizeTimer = null;
            $(window).bind('resize', function (){
                    if (resizeTimer) clearTimeout(resizeTimer);
                    resizeTimer = setTimeout(function(){
                        var _b_height = document.documentElement.clientHeight;
                        var toolbarHeight = $("#"+self.bstableId).parent().parent().prev().outerHeight(true);
                        var paginationHeight = $("#"+self.bstableId).parent().parent().next().outerHeight(true);
                        var _height = _b_height-t_top+self.subHeight-toolbarHeight-paginationHeight-13;
                        console.log(_b_height,toolbarHeight,paginationHeight)
                        $("#"+self.bstableId).parent().parent().height(_height);
                    } , 300);
            });
            */
        },
        setSubHeight:function(height){
            this.subHeight = height;
        },
        setHeight:function (height) {
            this.height = height;
        },
        setSubHead:function (head) {
            this.subHead = head;
        },
        /**
         * 是否显示表格搜索，此搜索是客户端搜索，不会进服务端
         * @param param
         */
        setSearch: function (search) {
            this.search = search;
        },

        /**
         * 设置搜索模式，设置为 true启用 全匹配搜索，否则为模糊搜索
         * @param param
         */
        setStrictSearch: function (strictSearch) {
            this.strictSearch = strictSearch;
        },

        /**
         * 是否单选checkbox
         * @param param
         */
        setSingleSelect: function (singleSelect) {
            this.singleSelect = singleSelect;
        },

        /**
         * 是否显示刷新按钮
         * @param param
         */
        setShowRefresh: function (showRefresh) {
            this.showRefresh = showRefresh;
        },
        /**
         * 是否显示所有的列
         * @param param
         */
        setShowColumns: function (showColumns) {
            this.showColumns = showColumns;
        },
        /**
         * 是否显示详细视图和列表视图的切换按钮
         * @param param
         */
        setShowToggle: function (showToggle) {
            this.showToggle = showToggle;
        },
        /**
         * 是否显示导出数据按钮
         * @param param
         */
        setShowExport: function (showExport) {
            this.showExport = showExport;
        },
        /**
         * 向后台传递的自定义参数
         * @param param
         */
        setQueryParams: function (param) {
            this.queryParams = param;
        },
        /**
         * 设置每页显示条数
         */
        setPageSize: function (pageSize) {
            this.pageSize = pageSize;
        },
        /**
         * 设置分页方式：server 或者 client
         */
        setPaginationType: function (type) {
            this.paginationType = type;
        },
        /**
         * 设置分页方式
         */
        setPagination: function (pagination) {
            this.pagination = pagination;
        },

        /**
         * 设置默认排序字段
         */
        setSortName: function (sortName) {
            this.sortName = sortName;
        },
        /**
         * 设置默认排序字段
         */
        setSortOrder: function (sortOrder) {
            this.sortOrder = sortOrder?sortOrder:"desc";
        },

        setSort: function (sortName,sortOrder) {
            this.sortName = sortName;
            this.sortOrder = sortOrder?sortOrder:"desc";
        },
        setRowStyle: function (rowStyle) {
            this.rowStyle = rowStyle;
        },

        setExportDataType: function (exportDataType) {
            this.exportDataType = exportDataType;
        },

        setIgnoreColumn: function (ignoreColumn) {
            this.ignoreColumn = ignoreColumn;
        },

        setExportFileName: function (exportFileName) {
            this.exportFileName = exportFileName;
        },

        setExportTableName: function (exportTableName) {
            this.exportTableName = exportTableName;
        },


        /**
         * 设置ajax post请求时候附带的参数
         */
        set: function (key, value) {
            this.queryParams[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
            return this;
        },

        setOnClickRow: function(func){
            this.onClickRow = func;
            return this;
        },
        setOnDblClickRow: function(func){
            this.onDblClickRow = func;
            return this;
        },
        setOnLoadSuccess: function(func){
            this.onLoadSuccess = func;
            return this;
        },
        /**
         * 清空ajax post请求参数
         */
        clear: function () {
            this.queryParams = {};
            return this;
        },

        /**
         * 销毁表
         */
        destroy: function(){
            $('#'+this.bstableId).bootstrapTable('destroy');
        },

        /**
         * 刷新 bootstrap 表格
         * Refresh the remote server data,
         * you can set {silent: true} to refresh the data silently,
         * and set {url: newUrl} to change the url.
         * To supply query params specific to this request, set {query: {foo: 'bar'}}
         */
        refresh: function (parms) {
            if (typeof parms != "undefined") {
                this.btInstance.bootstrapTable('refresh', parms);
            } else {
                this.btInstance.bootstrapTable('refresh');
            }
        }
    };

    window.CTDBSTable = CTDBSTable;

}());